<!-- 立项申请 -->
<template>
	<view class="page">
		<u--form
			labelPosition="top"
			:model="model"
			ref="ErpOmcProjectApplyForm"
			:rules="rules"
			labelWidth="auto"
			:labelStyle="{
				fontSize: '14px',
				color: '#B2B2B2',
				lineHight: '20px'
			}"
		>
			<view class="basic-style">
				<u-form-item
					label="单据编号"
					prop="projectNo"
					:borderBottom="false"
					required
				>
					<u--input
						disabled
						placeholder="请输入单据编号"
						v-model="model.projectNo"
					></u--input>
				</u-form-item>
				<u-form-item
					label="申请时间"
					prop="createTime"
					:borderBottom="false"
					required
				>
					<u--input
						v-model="model.createTime"
						disabled
						placeholder="请选择申请时间"
						border="surround"
						suffixIcon="calendar-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
					></u--input>
				</u-form-item>
				<u-form-item
					label="申请人"
					prop="proposer"
					:borderBottom="false"
					required
				>
					<h-select-person-input
						style="width: 100%"
						disabled
						v-model="model.proposer"
						placeholder="请选择申请人"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						objectField="model.proposer"
					></h-select-person-input>
				</u-form-item>
				<u-form-item
					label="申请部门"
					prop="proposerDeptId"
					:borderBottom="false"
					required
				>
					<h-select-depart-input
					  disabled
					  v-model="model.proposerDeptId"
					  :departName="model.proposerDeptText"
					  placeholder="请选择部门"
					  border="surround"
					  style="width: 100%"
					  suffixIcon="arrow-down-fill"
					  :suffixIconStyle="{ color: '#B2B2B2' }"
					  :title.sync="model.proposerDeptText"
					  @detail="ontenderDeptDetail"
					></h-select-depart-input>
				</u-form-item>
				<view class="basic-title-center">
					<u-line :length="120"></u-line>
					<view class="">基本信息</view>
					<u-line :length="120"></u-line>
				</view>
				<u-form-item
					label="数据来源"
					prop="isPrepareEstablish"
					:borderBottom="false"
					required
				>
					<h-dict-select
						style="width: 100%" 
						v-model="model.isPrepareEstablish" 
						placeholder="请选择数据来源" 
						dictName="omc_project_type" 
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
						@change="isPrepareEstablishChange"
					></h-dict-select>
					
				</u-form-item>
				<u-form-item
					v-if="model.isPrepareEstablish == '0'"
					label="预立项"
					prop="finalProjectId"
					:borderBottom="false"
					required
					@click="prepareProjectClick"
				>
					<h-select-project-input
					  v-model="model.finalProjectId"
					  style="width: 100%"
					  placeholder="请选择预立项"
					  objectField="model.finalProjectId"
					  border="surround"
					  :tenderStatus="'0'"
					  :projectStatus="'1'"
					  :changeStatus="'unchanged'"
					  suffixIcon="arrow-down-fill"
					  :suffixIconStyle="{ color: '#B2B2B2' }"
					  @input="prepareProjectChange"
					  
					></h-select-project-input>
				</u-form-item>
				
				 
				<u-form-item
					v-if="model.isPrepareEstablish == '1'"
					label="投标档案"
					prop="tenderFinalCode"
					:borderBottom="false"
				>
					<h-select-omc-project-tender-input
						v-model="model.tenderFinalCode"
						style="width: 100%"
						placeholder="请选择投标档案"
						objectField="model.tenderFinalCode"
						border="surround"
						:isBid="1"
						:query-type="'prepare'"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						@input="tenderFinalChange"
					></h-select-omc-project-tender-input>
				</u-form-item>
				
				<u-form-item
					label="项目名称"
					prop="projectName"
					:borderBottom="false"
					required
				>
					<u--input
						v-model="model.projectName"
						placeholder="请输入项目名称"
						border="surround"
					></u--input>
				</u-form-item>
				<u-form-item
					label="经营团队"
					prop="teamName"
					:borderBottom="false"
					required
				>
					<h-select-team-input
					  @input="changeBusinessCompany"
						style="width: 100%;"
						v-model="model.teamName"
						objectField="model.teamName"
						placeholder="请选择经营团队"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						:tdlx="1"
					></h-select-team-input>
				</u-form-item>
				<!-- <u-form-item
				label="经营公司"
				prop="businessCompanyId"
				:borderBottom="false"
				required>
				<h-select-company-input
					disabled
					style="width: 100%"
					v-model="model.businessCompanyId"
					border="surround"
					placeholder="请选择经营公司"
					suffixIcon="arrow-down-fill"
					:suffixIconStyle="{color: '#B2B2B2'}"
					objectField = 'managerTrusteeForm.gsdaId'
				></h-select-company-input>
              </u-form-item> -->
				<u-form-item
					label="项目承接人"
					prop="undertaker"
					:borderBottom="false"
					required
				>
					<h-select-person-input
						style="width: 100%"
						v-model="model.undertaker"
						placeholder="请选择项目承接人"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						objectField="model.undertaker"
					></h-select-person-input>
				</u-form-item>
				
				<u-form-item
					label="立项日期"
					prop="projectEstablishDate"
					:borderBottom="false"
					required
				>
					<h-time-select
					  v-model="model.projectEstablishDate"
					  placeholder="请选择立项日期"
					  border="surround"
					  suffixIcon="calendar-fill"
					  :suffixIconStyle="{ color: '#B2B2B2' }"
					  mode="datetime"
					></h-time-select>
				</u-form-item>
				
				<u-form-item
					label="签订单位"
					prop="signUnit"
					:borderBottom="false"
					required
				>
					<h-select-company-input
						style="width: 100%;"
						v-model="model.signUnit"
						objectField="model.signUnit"
						placeholder="请选择签订单位"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
					></h-select-company-input>
				</u-form-item>
				<u-form-item
					label="业绩归属年度"
					prop="year"
					:borderBottom="false"
					required
				>
					<h-dict-select
						style="width: 100%" 
						v-model="model.year" 
						placeholder="请选择业绩归属年度" 
						dictName="yjgsnd" 
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
					></h-dict-select>
				</u-form-item>
				<u-form-item
					label="是否环评项目"
					prop="isEnvironmentalAssessmentProject"
					:borderBottom="false"
					required
				>
					<h-dict-radio v-model="model.isEnvironmentalAssessmentProject" dictName="YES_OR_NO"></h-dict-radio>
				</u-form-item>
				<u-form-item
					label="业主单位"
					prop="ownerUnit"
					:borderBottom="false"
					required
				>
					<h-select-customer-input
						style="width: 100%"
						v-model="model.ownerUnit"
						commercialType= "1"
						border="surround"
						placeholder="请选择业主单位"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						objectField = 'model.ownerUnit'
						@input="onCustomerChange"
					></h-select-customer-input>
				</u-form-item>
				<u-form-item
					label="联系人"
					prop="contacts"
					:borderBottom="false"
					required
				>
					<h-dict-select
						style="width: 100%" 
						v-model="model.contacts" 
						placeholder="请选择联系人" 
						:dictName="cust_lxr" 
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
						@change="lxrChange"
					></h-dict-select>
				</u-form-item>
				<u-form-item
					label="联系方式"
					prop="contactTel"
					:borderBottom="false"
					required
				>
					<u--input
						v-model="model.contactTel"
						placeholder="请输入联系方式"
						border="surround"
					></u--input>
				</u-form-item>
				<u-form-item
					label="业主角色"
					prop="ownerRole"
					:borderBottom="false"
					required
				>
					<h-dict-select
						style="width: 100%" 
						v-model="model.ownerRole" 
						placeholder="请选择业主角色" 
						dictName="owner_role" 
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
					></h-dict-select>
				</u-form-item>
				<u-form-item
					label="企业类型"
					prop="enterpriseType"
					:borderBottom="false"
					
				>
				<h-dict-select
						style="width: 100%" 
						disabled
						v-model="model.enterpriseType" 
						placeholder="请选择企业类型" 
						dictName="enterprise_type" 
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
					></h-dict-select>
		
				</u-form-item>
				<u-form-item
					label="项目所在地址"
					prop="areaCode"
					:borderBottom="false"
					required
				>
					<h-select-address-input
						style="width: 100%"
						v-model="model.areaCode"
						placeholder="请选择项目地址"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
					></h-select-address-input>
				</u-form-item>
				<u-form-item
					label="项目详细地址"
					prop="projectAddress"
					:borderBottom="false"
					required
				>
					<u--input
						placeholder="请输入项目详细地址"
						v-model="model.projectAddress"
					></u--input>
				</u-form-item>
				<u-form-item
					label="项目来源"
					prop="projectSource"
					:borderBottom="false"
					ref="item1"
					required
				>
					<h-dict-select
						style="width: 100%" 
						v-model="model.projectSource" 
						placeholder="请选择项目来源" 
						dictName="xmly_type"
						suffixIcon="arrow-down-fill" 
						:suffixIconStyle="{color: '#B2B2B2'}"
					></h-dict-select>
				</u-form-item>
				<u-form-item
					label="预计合同额(元)"
					prop="estimatedContractAmount"
					:borderBottom="false"
					ref="item1"
					required
				>
					<u--input
						type="number"
						placeholder="请输入预计合同额"
						v-model="model.estimatedContractAmount"
						@change="convertMoney2"
						@blur="convertMoneyBlur2"
					></u--input>
				</u-form-item>
				<u-form-item
					label="预计合同额大写"
					prop="estimatedContractcapitalChineseAmount"
					:borderBottom="false"
					ref="item1"
				>
					<u--input
						disabled
						placeholder="请输入预计合同额大写"
						v-model="model.estimatedContractcapitalChineseAmount"
					></u--input>
				</u-form-item>
				<u-form-item
					label="经营绩效(元)"
					prop="businessPerformance"
					:borderBottom="false"
					ref="item1"
					required
				>
					<h-money-input
						type="number"
						placeholder="请输入经营绩效"
						v-model="model.businessPerformance"
					></h-money-input>
				</u-form-item>

				
				<u-form-item
					label="立项事由及说明"
					prop="establishReason"
					:borderBottom="false"
					ref="item1"
				>
					<u--textarea
						v-model="model.establishReason"
						:confirmType="null"
						count
						placeholder="请输入立项事由及说明"
						:maxlength="500"
					></u--textarea>
				</u-form-item>
			</view>
		</u--form>
		
		<!-- 附件 -->
		<view class="basic-style">
			<view class="basic-title-center">
				<u-line :length="120"></u-line>
				<view class="">相关附件</view>
				<u-line :length="120"></u-line>
			</view>
			<view class="warning">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
			<view class="" style="width: 100%;">
				<h-upload-file v-model="model.attachment" :isIcon="false" ></h-upload-file>
				<file-list v-if="model.attachment" v-model="model.attachment" :isDelete="true"></file-list>
			</view>
		</view>
		<view class="basic-style">
			<view class="basic-title-center">
				<u-line :length="105"></u-line>
				<view class="">任务信息</view>
				<u-line :length="105"></u-line>
			</view>
			<u-form-item label="分配方式" prop="distributionMethod" :borderBottom="false" required>
					<h-select-input-tag 
					style="width: 100%;"
					  v-model="model.distributionMethod"
					  placeholder="请选择分配方式"
					  dictName="distribution_method"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						@change="getForMoney()"/>
				</u-form-item>
				<u-form-item
					label="主生产团队"
					prop="mainProductionTeam"
					:borderBottom="false"
					required
				>
					<h-select-team-input
						style="width: 100%;"
						v-model="model.mainProductionTeam"
						objectField="model.mainProductionTeam"
						placeholder="请选择主生产团队"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						:tdlx="1"
					></h-select-team-input>
				</u-form-item>
			<ErpMyOmcProjectTaskForm btnShow @ok="onInforList" ref="projectTaskFormConfig" 
			:assignedAmount="model.estimatedContractAmount" :distributionMethod='model.distributionMethod' :dataList="dataSource"/>
		</view>
		<view class="space-x-1 px-1 btn_position">
			<u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDrafts"></u-button>
			<u-button :disabled="isSubmit"  type="primary"  text="保存并提交" @click="onSubmit"></u-button>
		</view>
		<view style="height: 100rpx;"></view>
		<u-toast ref="uToast"></u-toast>
		<ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
	</view>
</template>

<script>
import fileList from '@/pages/synergy/components/fileList.vue'
import ErpMyOmcProjectTaskForm from './components/ErpMyOmcProjectTaskForm.vue' // 业务分类组件
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
import http from '@/utils/request/index'
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
import {
	generatedFormNumber, // 获取单据编号
	erpOmcCustomerManagerContactId, // 获取联系方式
	erpOmcProjectApplyAdd, // 添加
	erpOmcProjectApplyEdit, // 编辑
	erpOmcProjectApplyQueryById, // 详情
	erpOmcProjectApplyQueryByProjectId ,// 获取业务分类信息列表
	erpOmcProjectApplyQueryTenderResultByEntity,
	erpOmcProjectApplyQueryTenderServiceListByTenderId,
	erpOmcProjectTaskListById,
	erpOmcProjectCheckProjectTenderEnd // 校验该预立项是否存在
} from '@/api/index.js'
import moment from 'moment'
import {
	BASE_URL
} from '@/utils/baseUrl.js'
import { convertCurrency } from '@/utils/MoneyConvert' // 金额大写转换
// 校验项目名称是否唯一
var projectId = ''
let checkProjectName = (rule, value, callback) => {
  if (!value) {
    return
  }
  let params = {
    projectName: value,
		projectId: projectId,
    type: 'project' // 立项：project  预立项：prepare
  }
  http.get('/api/erp/omc/project/erpOmcProject/checkProjectDuplicate', params).then(res => {
    if (res.success) {
      callback();
    } else {
      callback(new Error(res.message));
    }
  }).catch(error => {
    callback(new Error(error.message));
  })
}
export default {
	components: {
		fileList,
		ErpMyOmcProjectTaskForm,
		ProcessNodeConfiguration
	},
	data() {
		return {
			dictOptions: {},
			isFinalProjectId: false, // 用于判断编辑的时候不执行预立项详情
			isSubmit: false,
			model: {
				applyType: '1',
				lx: '1',
				businessCompanyId: '', // 经营公司
				projectNo: '', //单据编号
				createTime: '', // 申请时间
				proposer: '', // 申请人
				proposerDeptId: '', // 申请部门
				mainProductionTeam:'',
				isPrepareEstablish: '', // 数据来源
				finalProjectId: '', // 预立项
				tenderFinalCode: '', // 投标档案
				projectName: '', // 项目名称
				teamName: '', // 经营团队
				undertaker: '', // 项目承接人
				projectEstablishDate: '', // 立项日期
				signUnit: '', //签订单位
				year: '', // 业绩发归属年度
				isEnvironmentalAssessmentProject: '', //是否环评项目
				ownerUnit: '', // 业主单位
				contacts: '', // 联系人
				contactTel: '', // 联系方式
				areaCode: '', // 项目所在地址
				enterpriseType: '', //
				ownerRole: '', // 
				projectAddress: '', // 项目详细地址
				projectSource: '' ,// 项目来源
				estimatedContractAmount: '', // 预计合同额
				estimatedContractcapitalChineseAmount: '', // 预计合同额大写
				businessPerformance: '', // 经营绩效
				distributionMethod:'',//分配方式
				establishReason : '', // 立项事由及说明
				attachment: '', // 相关附件
			},
			cust_lxr: 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=0',
			id: '', // 详情id值
			dataSource: [], // 业务分类信息列表
			rules: {
				projectNo: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
				proposerDeptId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
				proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
				createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
				distributionMethod:[ { required: true, message: '请选择分配方式!',trigger: ['blur', 'change'] }],
				isEnvironmentalAssessmentProject: [
					{ required: true, message: '请选择是否环评!', trigger: ['change','blur'], },
				],
				finalProjectId: [
					{ required: true, message: '请选择预立项!', trigger: ['change','blur'], },
				],
				projectName: [
					{ required: true, message: '请输入项目名称!', pattern: '[^ \x22]+', trigger: ['change','blur'] },
					{ validator: checkProjectName, trigger: ['blur'] }
				],
				teamName: [
					{ required: true, message: '请选择经营团队!', trigger: ['change','blur'], },
				],
				undertaker: [
					{ required: true, message: '请选择项目承接人!', trigger: ['change','blur'], },
				],
				projectEstablishDate: [
					{ required: true, message: '请选择立项日期!', trigger: ['change','blur'], },
				],
				signUnit: [
				  { required: true, message: '请选择签订单位!', trigger: ['change','blur'], },
				],
				year: [
				  { required: true, message: '请选择业绩归属年度!', trigger: ['blur', 'change'], },
				],
				ownerUnit: [
				  { required: true, message: '请选择业主单位!', trigger: ['change','blur'], },
				],
				contacts: [
				  { required: true, message: '请选择联系人!', trigger: ['change','blur'], },
				],
				areaCode: [
					{ required: true, message: '请选择项目区域!', trigger: ['change','blur'], },
				],
				ownerRole: [
					{ required: true, message: '请选择业主角色!', trigger: ['change','blur'], },
				],
				projectAddress: [
					{ required: true, message: '请输入项目所在地址!', trigger: ['change','blur'] },
				],
				projectSource: [
					{ required: true, message: '请选择项目来源!', trigger: ['change','blur'], },
				],
				mainProductionTeam: [
					{ required: true, message: '请选择主生产团队!', trigger: ['change','blur'], },
				],
				estimatedContractAmount: [
				  { type: 'number', required: true, message: '请输入预计合同额!', trigger: ['blur'] },
				],
				businessPerformance: [
				  { type: 'number', required: true, message: '请输入经营绩效!', trigger: ['blur'] },
				],
				contactTel: [
					{ required: true, message: '请输入联系方式!', trigger: ['change', 'blur'], },
					{ pattern: /(^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$)|(^\/$)/, message: '请输入正确的联系方式!', trigger: ['change', 'blur'], }
				],
				// 2022/10/27 - 迭代11需求
				isPrepareEstablish: [
					{ required: true, message: '请选择数据来源!', trigger: ['change','blur'], },
				],
			},
			
			//代码生成后需手动设置流程编码
			flowCode: 'dev_erp_omc_project_apply_001',
			//代码生成后需手动设置流程编码
			flowCodeApply: 'dev_erp_omc_project_apply_001',
			formUrlApply: '/erp/omc/project/modules/ErpOmcProjectApplyForm',
			//代码生成后需手动设置流程编码
			flowCodeChange: 'dev_erp_omc_project_apply_002',
			formUrlChange: '/erp/omc/project/modules/ErpOmcProjectChangeForm',
			formUrl: '/erp/omc/project/modules/ErpOmcProjectApplyForm',
			beanName: 'erpOmcProjectApplyServiceImpl',
			formUrlMobile: '/pages/synergy/erpOmcProjectApplyList',
			superFieldList: [],
			formDisabled: false,
			lx: 1,
			processId: '1469208959040917506'
		};
	},
	onLoad(options) {
		this.id = options.id || ''
		if (options.id) {
			// 编辑
			this.edit(options.id)
			
		} else {
			// 添加
			this.add()
		}
		this.initDictConfig()
	},
	methods: {

		changeBusinessCompany(val){
      this.model.businessCompanyId = val.belongCompanyId
      },

	  changeMainProductionTeam(val) {
		this.model.mainProductionTeam =val.belongCompanyId
    //   this.$set(this.model, 'mainProductionTeam',val[0].belongCompanyId)
    },

		// 加载数据字典信息
		initDictConfig() {
			initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
				if (res.success) {
					this.$set(this.dictOptions, 'productTeam', res.result)
				}
			})
		},
		
		// 编辑
		async edit(id) {
			// 获取详情
			this.getDetail(id)
			erpOmcProjectTaskListById({ id: id }).then(res => {
				if (res.length > 0) {
					this.dataSource = res || res.result;
				}
			})
			
		},
		// 获取详请
		getDetail (id) {
			erpOmcProjectApplyQueryById({ id }).then(res => {
				if (res.success) {
					this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + res.result.ownerUnit + '\'';
					this.model = {...res.result};
					projectId = this.model.finalProjectId
					this.model.contacts = res.result.contacts
					this.model.contactTel = res.result.contactTel
					if (this.model.estimatedContractAmount) {
						this.$set(this.model, 'estimatedContractcapitalChineseAmount', convertCurrency(this.model.estimatedContractAmount))
						this.model.estimatedContractAmount = this.model.estimatedContractAmount.toFixed(2)
					}
					// this.$set(this.model, 'estimatedContractAmount', money.toFixed(2))
				}
			})
		},
		
		// 获取流程列表
		getProcessList (id) {
				let formUrl = this.formUrlApply;
				let flowCode = this.flowCodeApply;
				//判定流程的类型
				if (this.model.lx) {
					if (this.model.lx == 2) {
						formUrl = this.formUrlChange;
						flowCode = this.flowCodeChange;
					}
				}
				var projectId = this.model.finalProjectId ? this.model.finalProjectId : this.model.projectId
				// 校验该预立项是否存在，如果存在则无法提交
				erpOmcProjectCheckProjectTenderEnd({ id: projectId, type: this.model.lx, isPrepareEstablish: this.model.isPrepareEstablish }).then(res => {
					if (res.success) {
						this.$refs.processConfig.showPopup = true
						this.$refs.processConfig.formUrl = formUrl
						this.$refs.processConfig.formUrlMobile = this.formUrlMobile
						this.$refs.processConfig.flowCode = flowCode
						this.$refs.processConfig.edit(id, this.processId, this.beanName)
					} else {
						this.$refs.uToast.show({
							message: res.message,
							complete () {
								if (getCurrentPages().length > 1) {
									uni.navigateBack()
								} else {
									uni.reLaunch({
										url: '/pages/home/home'
									})
								}
								
							}
						})
					}
				})
			
		},
		
		// 投标部门详情
		ontenderDeptDetail(item) {
		  var title = ''
		  if (item && item.length) {
		    item.map((value, index) => {
		      title = value.departName + ',' + title
		    })
		    title = title.substring(0, title.lastIndexOf(','))
		  }
		  this.model.proposerDeptText = title
		},
		
		isPrepareEstablishChange () {
			this.resetBasicsPortionDataForm()
			projectId = ''
		},
		// 重置表单中基本信息部分数据
		resetBasicsPortionDataForm() {
			this.$set(this.model, 'finalProjectId', '')
			this.$set(this.model, 'projectName', '')
			this.$set(this.model, 'teamName', '')
			this.$set(this.model, 'businessCompanyId', '')
			this.$set(this.model, 'undertaker', '')
			this.$set(this.model, 'projectEstablishDate', '')
			this.$set(this.model, 'signUnit', '')
			this.$set(this.model, 'year', '')
			this.$set(this.model, 'ownerUnit', '')
			this.$set(this.model, 'contacts', '')
			this.$set(this.model, 'areaCode', '')
			this.$set(this.model, 'projectAddress', '')
			this.$set(this.model, 'projectSource', '')
			this.$set(this.model, 'estimatedContractAmount', '')
			this.$set(this.model, 'contactTel', '')
			this.$set(this.model, 'tenderFinalCode', '')
			this.$set(this.model, 'estimatedContractcapitalChineseAmount', '')
			this.$set(this.model, 'establishReason', '')
			this.$set(this.model, 'attachment', null)
			this.dataSource = []
			
			this.$refs.ErpOmcProjectApplyForm.clearValidate() // 清空校验结果
		},
		
		// 点击预立项
		prepareProjectClick () {
			this.isFinalProjectId = true
		},
		
		// 选择预立项
		prepareProjectChange (project) {
			console.log(project,'project---')
			// 人为的判断是否点击改变值
			if (!this.isFinalProjectId) {
				// 当点击编辑的时候，不执行下面
				return false
			}
			// this.customer_contacts = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0'
			this.$set(this.model, 'finalProjectId', project.id)
			projectId = project.id
			this.$set(this.model, 'prepareProjectId', project.prepareProjectId)
			this.$set(this.model, 'projectName', project.projectName)
			this.$set(this.model, 'bpmBizTitle', project.projectName)// 标题
			this.$set(this.model, 'projectType', project.projectType)
			this.$set(this.model, 'teamName', project.oldTeamId ? project.oldTeamId : project.teamName)
			this.$set(this.model, 'businessCompanyId', project.businessCompanyId)
			this.$set(this.model, 'undertaker', project.undertaker)
			this.$set(this.model, 'isBidding', project.isBidding)
			this.$set(this.model, 'isEnvironmentalAssessmentProject', project.isEnvironmentalAssessmentProject)
			this.$set(this.model, 'signUnit', project.signUnit)
			this.$set(this.model, 'year', project.year + '')
			this.$set(this.model, 'ownerUnit', project.ownerUnit)
			this.$set(this.model, 'contacts', project.contacts)
			this.$set(this.model, 'contactTel', project.contactTel)
			this.$set(this.model, 'areaCode', project.areaCode)
			this.$set(this.model, 'projectAddress', project.projectAddress)
			this.$set(this.model, 'projectSource', project.projectSource)
			this.$set(this.model, 'estimatedContractAmount', project.estimatedContractAmount)
			this.$set(this.model, 'distributionMethod', project.distributionMethod)
			this.$set(this.model, 'estimatedContractcapitalChineseAmount', project.estimatedContractcapitalChineseAmount)
			this.$set(this.model, 'establishReason', project.establishReason)
			this.$set(this.model, 'attachment', project.attachment)
			this.$set(this.model, 'enterpriseType', project.enterpriseType)
			
			
			this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.ownerUnit + '\'';
			// 根据项目id 查看业务分类
			this.dataSource = []
			erpOmcProjectApplyQueryByProjectId({ projectId: this.model.finalProjectId }).then(res => {
				if (res.success) {
					this.dataSource = res.result.records || res.result
				}
			})
			this.model.lx = 1;
			this.convertMoneyBlur2(project.estimatedContractAmount)
			this.$refs.ErpOmcProjectApplyForm.clearValidate() // 清空校验结果
			
			this.isFinalProjectId = false
		},
		
		// 投标档案选择
		tenderFinalChange(tenderFinal) {
			console.log(tenderFinal,'tenderFinal---')
			// fix:BUG499 立项中的数据由投标档案中带出 start
			this.$set(this.model, 'finalProjectId', tenderFinal.prepareProjectId); // 项目id
			projectId = tenderFinal.prepareProjectId
			this.$set(this.model, 'prepareProjectId', tenderFinal.prepareProjectId); // 项目id
			this.$set(this.model, 'teamName', tenderFinal.businessTeam); // 经营团队
			this.$set(this.model, 'businessCompanyId', tenderFinal.businessCompanyId); // 经营公司
			this.$set(this.model, 'undertaker', tenderFinal.undertaker); // 项目承接人
			this.$set(this.model, 'year', tenderFinal.year + ''); // 业绩归属年度
			this.$set(this.model, 'ownerUnit', tenderFinal.ownerUnit); // 业主单位
			this.$set(this.model, 'enterpriseType', tenderFinal.enterpriseType)
			this.$set(this.model, 'contacts', tenderFinal.ownerLinkman); // 联系人（立项）-》业主联系人（投标申请）
			this.$set(this.model, 'contactTel', tenderFinal.ownerTel); // 联系方式（立项）-》业主联系方式（投标）
			this.$set(this.model, 'areaCode', tenderFinal.projectAddress); // 项目所在地址（立项）-》项目地址（投标申请）
			this.$set(this.model, 'projectAddress', tenderFinal.detailedAddress); // 项目所在地址（立项）-》项目地址（投标申请）
			this.$set(this.model, 'projectName', tenderFinal.projectName); // 项目名称
			
			// 迭代12 签订单位（对应投标档案中的投标单位）
			this.$set(this.model, 'signUnit', tenderFinal.tenderUnit); // 签订单位
			this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.ownerUnit + '\'';
			this.$set(this.model, 'isBidding', '1'); // 已投标
			// 迭代12查看为中标的投标金额
			let param = {
			tenderId: tenderFinal.id,
			bidResult: '1'
			}
			erpOmcProjectApplyQueryTenderResultByEntity(param).then((res) => {
			if (res.success) {
				this.$set(this.model, 'estimatedContractAmount', res.result.tenderAmount)
				this.convertMoney2()
			}
			})
			this.model.lx = 1;
			// 子表（立项）-》业务分类子表（投标申请）
			erpOmcProjectApplyQueryTenderServiceListByTenderId({ id: tenderFinal.id }).then((res) => {
				if (res.success) {
				  if (!!res.result && res.result.length > 0) {
					let list = res.result.map((record) => {
					  return { categoryCode: record.serviceType, categoryName: record.serviceName, id: record.id }
					})
					this.dataSource = list;
				  } else {
					this.dataSource = [];
				  }
				}
			})
			this.convertMoneyBlur2(tenderFinal.estimatedContractAmount)
			this.$refs.ErpOmcProjectApplyForm.clearValidate() // 清空校验结果
		},
		
		// 添加
		add() {
			this.getGeneratedFormNumber()
			this.model.createTime = moment().format('YYYY-MM-DD HH:mm'); // 申请时间
			this.model.proposer = uni.getStorageSync('userInfo').empId; //申请人
			this.model.proposerDeptId = uni.getStorageSync('userInfo').deptId; //申请部门
			projectId = ''
		},
		// 获取单据编号
		getGeneratedFormNumber() {
			generatedFormNumber({ prefix: 'LX', subSystemCode: '05' }).then(res => {
				if (res.success) {
					this.$set(this.model, 'projectNo', res.result)
				}
			})
		},
		
		// 修改本次合同额大写和修改任务信息中的合同占比
		convertMoney2(item) {
			if (this.model.estimatedContractAmount === null
				|| this.model.estimatedContractAmount === ''
				|| this.model.estimatedContractAmount === undefined) {
					this.$set(this.model, 'estimatedContractcapitalChineseAmount', '')
				return false
			}
			let money = Number(this.model.estimatedContractAmount)
			this.$set(this.model, 'estimatedContractcapitalChineseAmount', convertCurrency(money))
			
			this.getForMoney()
			
		},
		getForMoney(){
		  if(this.dataSource.length>0){
	
			this.dataSource.forEach(item =>{
	
			  if(parseInt(this.model.estimatedContractAmount)===0){
				item.contractAmount = 0
				item.contractRate = 0
				
			  }else{
	
				if(!this.model.estimatedContractAmount){
				  return
				}
	
				if(this.model.distributionMethod=='1'){
				  // 按比例：更改预计合同额，占比不变、对应的分配合同额实时变化
				  if(item.contractRate){
	
					let amount = this.model.estimatedContractAmount * item.contractRate / 100
					item.contractAmount = Math.round((amount + Number.EPSILON) * 100) / 100
	
					// item.contractAmount = parseFloat(item.contractRate*0.01*parseFloat(this.model.estimatedContractAmount)).toFixed(2)
	
				  }
	
			  }else if(this.model.distributionMethod=='2'){
				// 按金额：更改预计合同额，分配合同额不变、对应的占比实时变化
				if(item.contractAmount){
	
				  let rate = item.contractAmount / this.model.estimatedContractAmount * 100
				  item.contractRate = Math.round((rate + Number.EPSILON) * 100) / 100
					// item.contractRate = parseFloat(parseFloat(item.contractAmount) / parseFloat(this.model.estimatedContractAmount)*100).toFixed(2)
				  }
				}
	
			  }
	
			})
		  }
		},
		// 监听修改本次合同额数据
		convertMoneyBlur2 (item) {
			if (this.model.estimatedContractAmount === null
				|| this.model.estimatedContractAmount === ''
				|| this.model.estimatedContractAmount === undefined) {
					this.$set(this.model, 'estimatedContractcapitalChineseAmount', '')
				return false
			}
			let money = Number(this.model.estimatedContractAmount)
			if (money <= 0) {
				money = 0
			}
			this.$set(this.model, 'estimatedContractAmount', money.toFixed(2))
			this.convertMoney2()
		},
		
		// 选择业主单位
		onCustomerChange (val) {
			console.log(val,'val---');
			
			this.$set(this.model, 'contacts', null)
			this.$set(this.model, 'contactTel', null)
			this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.ownerUnit + '\'';
			this.model.enterpriseType = val.enterpriseType
		},
		// 选择联系人
		lxrChange (val) {
			var params = {id: val}
			erpOmcCustomerManagerContactId(params).then(res => {
				if (res.success) {
					this.$set(this.model, 'contactTel', res.result.lxfs)
				} else {
					this.$refs.uToast.show({
						message: res.message,
						type: 'error'
					})
				}
			})
		},
		
		onInforList (item,type) {
			let params = JSON.parse(JSON.stringify(item))
			// 区分编辑or新增
			if(type=='add'){
				this.dataSource.push(params)
			}else if(type=='edit'){
				this.dataSource.map((value, index) => {
					if (value.id == params.id) {
						this.dataSource[index] = params
					}
				})
			}else if(type=='delete'){
				this.dataSource.splice(item, 1)
			}
		},
		
		validateForm() {
			return this.$refs.ErpOmcProjectApplyForm.validate().then(async () => {
				var that = this
				if (this.model) {
					if (this.model.isPrepareEstablish === '0') {
					  if (!this.model.projectName) {
						this.$refs.uToast.show({
							message: '项目名称不可为空！',
							type: 'error'
						})
						return Promise.reject("项目名称不可为空")
					  }
					} else {
					  this.dataSource.forEach((item, index) => {
						if (item.id) {
						  item.oldId = item.id
						}
					  })
					}
				}
				let params = {
					projectName: that.model.projectName,
					projectId: projectId,
					type: 'project' // 立项：project  预立项：prepare
				}
				var isCheckProjectDuplicateText = await ''
				var isCheckProjectDuplicate = await
				http.get('/api/erp/omc/project/erpOmcProject/checkProjectDuplicate', params).then(async res => {
					// 如果验证不通过，需要在callback()抛出new Error('错误提示信息')
					isCheckProjectDuplicateText = res.message
					return res.success
				}).catch(async err => {
					isCheckProjectDuplicateText = err.message
					return false
				})
				if (!isCheckProjectDuplicate) {
					this.$refs.uToast.show({
										message: isCheckProjectDuplicateText,
										type: 'error'
									})
									return Promise.reject(isCheckProjectDuplicateText)
				}
				
								if (!this.dataSource || this.dataSource.length === 0) {
									this.$refs.uToast.show({
										message: '必须填写业务分类信息！',
										type: 'error'
									})
									return Promise.reject('必须填写业务分类信息！')
								}
								// 判断是按比例还是按金额
								if(this.model.distributionMethod=='1'){
								  let rate = 0
								  this.dataSource.forEach(val => {
									rate += parseFloat(val.contractRate)
								  })
								  if(rate!=100&&parseInt(this.model.estimatedContractAmount)!==0){
									  this.$refs.uToast.show({
									  	message: '合同占比相加不等于100%，请重新填写',
									  	type: 'error'
									  })
									return Promise.reject('合同占比相加不等于100%，请重新填写')
								  }
						
								}else if(this.model.distributionMethod=='2'){
								  let total = 0
								  this.dataSource.forEach(val => {
									total += parseFloat(val.contractAmount)
								  })
								  if (total.toFixed(2) != parseFloat(that.model.estimatedContractAmount).toFixed(2)) {
									this.$refs.uToast.show({
										message: '所有分配金额总计和预计合同额不相等，请重新填写！',
										type: 'error'
									})
									return Promise.reject('所有分配金额总计和预计合同额不相等，请重新填写！')
								  }
								}
								
								this.isSubmit = true
								var isJudge = -1
								for (var i = 0; i < this.dataSource.length; i++) {
									var isTrue = await http.get('/api/erp/omc/project/erpOmcProjectApply/valdateProductTeamLeader', { teamId: this.dataSource[i].productTeam }).then((res) => {
										if (res.success) {
											return res.success
										} else {
											isJudge = i
											var info = filterMultiDictText(this.dictOptions['productTeam'], this.dataSource[i].productTeam + '') + '团队，生产负责人岗位未找到'
											this.$refs.uToast.show({
												message: info,
												type: 'error'
											})
											return res.success
										}
									})
									if (!isTrue) {
										break
									}
								}
								this.isSubmit = false
								if (isJudge != -1) {
									return Promise.reject('生产负责人岗位未找到')
								}



				

				
				
				// return Promise.resolve()
			})
		},
		// 点击提交
		async onSubmit () {
			var that = this
			await this.validateForm()
			if(!this.model.distributionMethod) return 	this.$refs.uToast.show({message: '请填写分配方式',type: 'error'})
			if(!this.model.mainProductionTeam) return 	this.$refs.uToast.show({message: '请填写主生产团队',type: 'error'})
			this.isSubmit = true
			this.model.categoryList = this.dataSource;
			let httpurl = '';
			if (!this.model.id) {
				httpurl = erpOmcProjectApplyAdd;
			} else {
				httpurl = erpOmcProjectApplyEdit;
			}
			httpurl(this.model).then(res => {
				if (res.success) {
					var that = this
					// 获取流程列表
					if (this.id) {
						this.getProcessList(this.id)
					} else {
						// 判断添加的时候是否有返回id值
						if (res.result) {
							this.getProcessList(res.result)
						}
					}
					this.$refs.uToast.show({
						message: res.message,
						type: 'default',
						complete () {
							// that.isSubmit = false
						}
					})
				} else {
					this.$refs.uToast.show({
						message: res.message,
						type: 'error'
					})
				}
			})
		},
		
		async onDrafts() {
			var that = this
			// await this.validateForm()
			this.isSubmit = true
			this.model.categoryList = this.dataSource;
			let httpurl = '';
			if (!this.model.id) {
				httpurl = erpOmcProjectApplyAdd;
			} else {
				httpurl = erpOmcProjectApplyEdit;
			}
			httpurl(this.model).then(res => {
				if (res.success) {
					var that = this
					this.$refs.uToast.show({
						message: res.message,
						type: 'default',
						complete () {
							that.isSubmit = false
							if (getCurrentPages().length > 1) {
								uni.navigateBack()
							} else {
								uni.reLaunch({
									url: '/pages/home/home'
								})
							}
							
						}
					})
					
					
				} else {
					this.$refs.uToast.show({
						message: res.message,
						type: 'error'
					})
				}
			})
		},
		
		// 提交流程成功
		onOk () {
			this.$refs.uToast.show({
				message: '提交成功',
				type: 'success',
				complete () {
					if (getCurrentPages().length > 1) {
						uni.navigateBack()
					} else {
						uni.reLaunch({
							url: '/pages/home/home'
						})
					}
					
				}
			})
		}
	}
};
</script>

<style lang="scss" scoped>
@import url("@/assets/inputStyle.scss");
</style>